import {reactive, ref} from "vue";
import {login} from "@/api/user";
import router from "@/router";
import {ElNotification} from "element-plus";
import {getTimePeriod} from "@/utils/time.ts";
import {useLoginStore} from '@/store/usersLoginStore.ts'


export default function () {
    const loginStore = useLoginStore()
    let isLoading = ref(false)
    const loginFormRef = ref()
    let loginForm = reactive({
        loginName: '',
        userPassword: ''
    })
    const rulesLoginForm = {
        loginName: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        userPassword: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, message: '密码不能小于6位', trigger: 'blur'},
        ]
    }
    const loginSubmit = async (formEl: any) => {
        if (!formEl) return
        await formEl.validate((valid: any) => {
            if (valid) {
                isLoading.value = true
                // 登录逻辑
                login(loginForm).then(async res => {
                    if (res.code === 200) {
                        isLoading.value = false
                        localStorage.setItem('token', res.data.token)
                        const getUserInfo = await loginStore.getUserInfoFun()
                        if (getUserInfo != "ok") {
                            ElNotification({
                                message: getUserInfo,
                                type: 'error',
                            })
                            return
                        }
                        await router.push({name: 'Layout'})
                        ElNotification({
                            message: `欢迎回来，${loginStore.userName}`,
                            type: 'success',
                            title: `Hi，${getTimePeriod()}`
                        })
                    } else {
                        isLoading.value = false
                        ElNotification({
                            message: res.msg,
                            type: 'error',
                        })
                    }

                }).catch(() => {
                    isLoading.value = false
                })
            }
        })
    }
    return {loginFormRef, loginForm, rulesLoginForm, loginSubmit, isLoading}
}


